package com.xx.linkage.handler;

import cn.hutool.core.util.StrUtil;
import com.xx.domain.entity.DisposeLog;
import com.xx.netty.server.AisServer;
import com.xx.web.domain.dto.EnvDto;
import com.xx.web.domain.entity.DisposeRule;
import com.xx.web.proto.ShipOuterClass;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class VhfHandler extends AbstractDisposeHandler {
    protected boolean test(DisposeRule disposeRule) {
        return disposeRule.getVhf();
    }

    protected void accept(DisposeRule disposeRule, ShipOuterClass.Ship ship, EnvDto envDto, DisposeLog disposeLog) {
        // 开启 VHF
        if (disposeRule.getVhf()&& StringUtils.isNotBlank(disposeRule.getVhfContent())) {
            if (AisServer.clientChannel != null) {
                ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
                    String tts = "$--TTS,01,16,0,{}*hh\r\n";
                    String content = StrUtil.format(disposeRule.getVhfContent(), StringUtils.isNotBlank(ship.getChineseName()) ? ship.getChineseName() : ship.getName());
                    disposeLog.setVhfContent(content);
                    disposeLog.setSave(true);
                    String command = StrUtil.format(tts, content);
                    if (AisServer.clientChannel.isActive()) {
                        AisServer.clientChannel.writeAndFlush(buffer.writeBytes(command.getBytes())).addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (future.isSuccess()) {
                                    // 发送成功
                                    log.info("vhf: {} has been sent successfully.", command);
                                } else {
                                    // 发送失败
                                    log.error("Failed to send {}: {}", command, future.cause());
                                }
                            }
                        });
                    }else{
                        log.error("发送vhf失败,通道已关闭");
                    }
            }
        }
    }
}
